import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gameplay_flutter/lib_runtime/extension/string_extension/string_text.dart';
import 'package:gameplay_flutter/m_room/constants/room_assets.dart';

import '../../m_me/constants/me_assets_constants.dart';

class RoomMsg extends StatefulWidget {
  const RoomMsg({Key? key}) : super(key: key);

  @override
  _RoomMsgPageState createState() => _RoomMsgPageState();
}

class _RoomMsgPageState extends State<RoomMsg> {
  final ScrollController _scrollController = ScrollController();
  bool _isAtBottom = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_scrollListener);
    // 初始滚动到底部
    WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToBottom());
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Padding(
        padding: EdgeInsetsDirectional.only(top: 20.h,start: 15.w,end: 84.w),
        child: ListView.builder(
          controller: _scrollController,
          itemCount: 30,
          itemBuilder: (context, index) {
            switch (index % 3) {
              case 0:
                return _msgNotice();
              case 1:
                return _msgChat();
              case 2:
                return _msgGift();
            }
            return _msgNotice();
          },
        ),
      ),
    );
  }

  void _scrollListener() {
    if (!_scrollController.hasClients) return;
    final position = _scrollController.position;
    final isBottom = position.pixels >= position.maxScrollExtent - 1e-3;
    if (isBottom != _isAtBottom) {
      setState(() => _isAtBottom = isBottom);
    }
  }

  void _scrollToBottom() {
    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }




  /// 公告消息
  Widget _msgNotice() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          decoration: BoxDecoration(
            color: const Color(0x0DFFFFFF),
            borderRadius: BorderRadius.circular(8.0.r),
          ),
          padding: EdgeInsets.all(14.0.r),
          margin: EdgeInsetsDirectional.only(bottom: 17.w),
          child: "欢迎来到房间".text(
            color: const Color(0xFFEFD298),
            fontSize: 14.sp,
            weight: TextFontWeight.regular,
          ),
        ),
      ],
    );
  }

  Widget _msgChat() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        _IdentityData(),
        Container(
          decoration: BoxDecoration(
            color: const Color(0x0DFFFFFF),
            borderRadius: BorderRadius.circular(8.0.r),
          ),
          margin: EdgeInsetsDirectional.only(start: 36.w),
          padding: EdgeInsets.all(14.0.r),
          child:
              "Welcome to our room ".text(
            color: Colors.white,
            fontSize: 14.sp,
            weight: TextFontWeight.regular,
          ),
        ),
        SizedBox(height: 8.h),
      ],
    );
  }

  Widget _msgGift() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _IdentityData(),
        UnconstrainedBox(
          child: Container(
            decoration: BoxDecoration(
              color: const Color(0x0DFFFFFF),
              borderRadius: BorderRadius.circular(8.0.r),
            ),
            margin: EdgeInsetsDirectional.only(start: 36.w),
            padding: EdgeInsets.all(14.0.r),
            child:Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                "Name of gift recipi...".text(
                  color: const Color(0xFFFFFFFF),
                  fontSize: 12.sp,
                  weight: TextFontWeight.medium,
                ),
                SizedBox(height: 8.h),
                Row(
                  children: [
                    CachedNetworkImage(
                      imageUrl: 'https://picsum.photos/200/300',
                      placeholder: (context, url) => CircularProgressIndicator(),
                      errorWidget: (context, url, error) => Icon(Icons.error),
                      width: 50.w,
                      height: 50.h,
                      fit: BoxFit.scaleDown,
                    ),
                    SizedBox(width: 8.w),
                    "X".text(
                      color: const Color(0xFFFFFFFF),
                      fontSize: 14.sp,
                      weight: TextFontWeight.medium,
                    ),
                    SizedBox(width: 5.w),
                    "99".text(
                      color: const Color(0xFFFFFFFF),
                      fontSize: 26.sp,
                      weight: TextFontWeight.medium,
                    ),
                  ]
                )
              ],
            )
          ),
        ),
        SizedBox(height: 8.h),
      ],
    );
  }

  Widget _IdentityData() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        CircleAvatar(
          backgroundColor: Color(0xFFFFFFFF),
          radius: 14.r,
          backgroundImage: CachedNetworkImageProvider('https://picsum.photos/200/300'),
          // 使用 NetworkImage
          child: true
              ? Image.asset(MeAssetsConstants.iconEmpty) // 如果没有图片，显示加载动画
              : null,
        ),
        SizedBox(width: 9.w),
        Image.asset(
          RoomAssets.roomIdentityIcon,
          width: 12.w,
          height: 14.h,
        ),
        "User Name".text(
          color: const Color(0xFFFFFFFF),
          fontSize: 16.sp,
          weight: TextFontWeight.medium,
        ),
      ],
    );
  }
}
